/**
 * useTools Composable
 * 
 * 用于管理 Cornerstone3D 工具的 Vue 组合式函数
 * 
 * @author yangzhixin
 * @module composables/useTools
 */

import { ref, computed, type Ref } from 'vue';
import type { CornerstoneFacade, ToolMode } from 'js-3d-model';

/**
 * 工具类型枚举
 */
export enum ToolType {
  WindowLevel = 'WindowLevel',
  Pan = 'Pan',
  Zoom = 'Zoom',
  StackScroll = 'StackScroll',
  Length = 'Length',
  Angle = 'Angle',
  RectangleROI = 'RectangleROI',
  EllipticalROI = 'EllipticalROI',
  CircleROI = 'CircleROI',
  Bidirectional = 'Bidirectional',
  ArrowAnnotate = 'ArrowAnnotate',
  Probe = 'Probe',
  FreehandROI = 'FreehandROI',
}

/**
 * 工具配置接口
 */
export interface ToolConfig {
  /** 工具组ID */
  toolGroupId: string;
  /** 视口ID列表 */
  viewportIds: string[];
}

/**
 * 工具激活选项
 */
export interface ActivateToolOptions {
  /** 工具名称 */
  toolName: string;
  /** 激活模式 */
  mode?: ToolMode;
  /** 鼠标按钮绑定 */
  bindings?: {
    mouseButton?: number;
    modifierKey?: string;
  };
}

/**
 * 标注数据接口
 */
export interface AnnotationData {
  /** 标注ID */
  annotationUID: string;
  /** 工具名称 */
  toolName: string;
  /** 标注数据 */
  data: any;
  /** 元数据 */
  metadata?: Record<string, any>;
}

/**
 * useTools 返回类型
 */
export interface UseToolsReturn {
  /** 工具组ID */
  toolGroupId: Ref<string | null>;
  /** 当前激活的工具 */
  activeTool: Ref<string | null>;
  /** 已注册的工具列表 */
  registeredTools: Ref<string[]>;
  /** 标注列表 */
  annotations: Ref<AnnotationData[]>;
  /** 是否正在加载 */
  isLoading: Ref<boolean>;
  /** 错误信息 */
  error: Ref<string | null>;
  /** 创建工具组 */
  createToolGroup: (config: ToolConfig) => Promise<void>;
  /** 注册工具 */
  registerTool: (toolName: string) => Promise<void>;
  /** 批量注册工具 */
  registerTools: (toolNames: string[]) => Promise<void>;
  /** 激活工具 */
  activateTool: (options: ActivateToolOptions) => Promise<void>;
  /** 停用工具 */
  deactivateTool: (toolName: string) => Promise<void>;
  /** 获取所有标注 */
  getAllAnnotations: (toolName?: string) => AnnotationData[];
  /** 删除标注 */
  removeAnnotation: (annotationUID: string) => Promise<void>;
  /** 清除所有标注 */
  clearAllAnnotations: (toolName?: string) => Promise<void>;
  /** 导出标注 */
  exportAnnotations: (format?: 'json' | 'csv') => Promise<string>;
  /** 导入标注 */
  importAnnotations: (data: string, format?: 'json' | 'csv') => Promise<void>;
  /** 销毁工具组 */
  destroyToolGroup: () => void;
}

/**
 * useTools - 工具注册和管理
 * 
 * 提供响应式的工具管理，包括工具注册、激活和标注管理
 * 
 * @param facade - CornerstoneFacade 实例
 * @returns 工具管理方法和状态
 * 
 * @example
 * ```vue
 * <script setup>
 * import { useTools } from '@/composables/useTools';
 * import { useCornerstone3D } from '@/composables/useCornerstone3D';
 * 
 * const { facade } = useCornerstone3D();
 * const { 
 *   createToolGroup, 
 *   registerTools, 
 *   activateTool 
 * } = useTools(facade);
 * 
 * onMounted(async () => {
 *   await createToolGroup({ 
 *     toolGroupId: 'default', 
 *     viewportIds: ['viewport-1'] 
 *   });
 *   await registerTools(['WindowLevel', 'Pan', 'Zoom']);
 *   await activateTool({ toolName: 'WindowLevel' });
 * });
 * </script>
 * ```
 */
export function useTools(
  facade: Ref<CornerstoneFacade | null>
): UseToolsReturn {
  // 响应式状态
  const toolGroupId = ref<string | null>(null);
  const activeTool = ref<string | null>(null);
  const registeredTools = ref<string[]>([]);
  const annotations = ref<AnnotationData[]>([]);
  const isLoading = ref(false);
  const error = ref<string | null>(null);

  /**
   * 创建工具组
   * 
   * @param config - 工具组配置
   */
  const createToolGroup = async (config: ToolConfig): Promise<void> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      isLoading.value = true;
      error.value = null;

      console.log('[useTools] 创建工具组:', config);

      await facade.value.createToolGroup({
        toolGroupId: config.toolGroupId,
      });

      // 添加视口到工具组
      for (const viewportId of config.viewportIds) {
        await facade.value.addViewportToToolGroup({
          toolGroupId: config.toolGroupId,
          viewportId,
        });
      }

      toolGroupId.value = config.toolGroupId;

      console.log('[useTools] 工具组创建成功:', toolGroupId.value);
    } catch (err: any) {
      console.error('[useTools] 创建工具组失败:', err);
      error.value = err.message || '创建工具组失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 注册单个工具
   * 
   * @param toolName - 工具名称
   */
  const registerTool = async (toolName: string): Promise<void> => {
    if (!facade.value || !toolGroupId.value) {
      throw new Error('工具组未创建');
    }

    try {
      console.log('[useTools] 注册工具:', toolName);

      await facade.value.registerTool({
        toolGroupId: toolGroupId.value,
        toolName,
      });

      if (!registeredTools.value.includes(toolName)) {
        registeredTools.value.push(toolName);
      }

      console.log('[useTools] 工具注册成功:', toolName);
    } catch (err: any) {
      console.error('[useTools] 注册工具失败:', err);
      error.value = err.message || '注册工具失败';
      throw err;
    }
  };

  /**
   * 批量注册工具
   * 
   * @param toolNames - 工具名称列表
   */
  const registerTools = async (toolNames: string[]): Promise<void> => {
    try {
      isLoading.value = true;
      error.value = null;

      for (const toolName of toolNames) {
        await registerTool(toolName);
      }

      console.log('[useTools] 批量注册工具成功:', toolNames);
    } catch (err: any) {
      console.error('[useTools] 批量注册工具失败:', err);
      error.value = err.message || '批量注册工具失败';
      throw err;
    } finally {
      isLoading.value = false;
    }
  };

  /**
   * 激活工具
   * 
   * @param options - 激活选项
   */
  const activateTool = async (options: ActivateToolOptions): Promise<void> => {
    if (!facade.value || !toolGroupId.value) {
      throw new Error('工具组未创建');
    }

    try {
      console.log('[useTools] 激活工具:', options);

      await facade.value.setToolActive({
        toolGroupId: toolGroupId.value,
        toolName: options.toolName,
        mode: options.mode || 'Active',
        bindings: options.bindings,
      });

      activeTool.value = options.toolName;

      console.log('[useTools] 工具激活成功:', options.toolName);
    } catch (err: any) {
      console.error('[useTools] 激活工具失败:', err);
      error.value = err.message || '激活工具失败';
      throw err;
    }
  };

  /**
   * 停用工具
   * 
   * @param toolName - 工具名称
   */
  const deactivateTool = async (toolName: string): Promise<void> => {
    if (!facade.value || !toolGroupId.value) {
      throw new Error('工具组未创建');
    }

    try {
      console.log('[useTools] 停用工具:', toolName);

      await facade.value.setToolPassive({
        toolGroupId: toolGroupId.value,
        toolName,
      });

      if (activeTool.value === toolName) {
        activeTool.value = null;
      }

      console.log('[useTools] 工具停用成功:', toolName);
    } catch (err: any) {
      console.error('[useTools] 停用工具失败:', err);
      error.value = err.message || '停用工具失败';
      throw err;
    }
  };

  /**
   * 获取所有标注
   * 
   * @param toolName - 可选的工具名称过滤
   * @returns 标注数据数组
   */
  const getAllAnnotations = (toolName?: string): AnnotationData[] => {
    if (!facade.value || !toolGroupId.value) {
      return [];
    }

    try {
      const allAnnotations = facade.value.getAllAnnotations({
        toolGroupId: toolGroupId.value,
        toolName,
      });

      annotations.value = allAnnotations || [];
      return annotations.value;
    } catch (err: any) {
      console.error('[useTools] 获取标注失败:', err);
      error.value = err.message || '获取标注失败';
      return [];
    }
  };

  /**
   * 删除标注
   * 
   * @param annotationUID - 标注唯一ID
   */
  const removeAnnotation = async (annotationUID: string): Promise<void> => {
    if (!facade.value) {
      throw new Error('Cornerstone3D 未初始化');
    }

    try {
      console.log('[useTools] 删除标注:', annotationUID);

      await facade.value.removeAnnotation({
        annotationUID,
      });

      // 更新本地标注列表
      annotations.value = annotations.value.filter(
        (a) => a.annotationUID !== annotationUID
      );

      console.log('[useTools] 标注删除成功');
    } catch (err: any) {
      console.error('[useTools] 删除标注失败:', err);
      error.value = err.message || '删除标注失败';
      throw err;
    }
  };

  /**
   * 清除所有标注
   * 
   * @param toolName - 可选的工具名称过滤
   */
  const clearAllAnnotations = async (toolName?: string): Promise<void> => {
    if (!facade.value || !toolGroupId.value) {
      throw new Error('工具组未创建');
    }

    try {
      console.log('[useTools] 清除所有标注:', toolName);

      await facade.value.clearAnnotations({
        toolGroupId: toolGroupId.value,
        toolName,
      });

      if (toolName) {
        annotations.value = annotations.value.filter(
          (a) => a.toolName !== toolName
        );
      } else {
        annotations.value = [];
      }

      console.log('[useTools] 标注清除成功');
    } catch (err: any) {
      console.error('[useTools] 清除标注失败:', err);
      error.value = err.message || '清除标注失败';
      throw err;
    }
  };

  /**
   * 导出标注
   * 
   * @param format - 导出格式
   * @returns 标注数据字符串
   */
  const exportAnnotations = async (format: 'json' | 'csv' = 'json'): Promise<string> => {
    if (!facade.value || !toolGroupId.value) {
      throw new Error('工具组未创建');
    }

    try {
      console.log('[useTools] 导出标注:', format);

      const data = await facade.value.exportAnnotations({
        toolGroupId: toolGroupId.value,
        format,
      });

      console.log('[useTools] 标注导出成功');
      return data;
    } catch (err: any) {
      console.error('[useTools] 导出标注失败:', err);
      error.value = err.message || '导出标注失败';
      throw err;
    }
  };

  /**
   * 导入标注
   * 
   * @param data - 标注数据字符串
   * @param format - 数据格式
   */
  const importAnnotations = async (
    data: string,
    format: 'json' | 'csv' = 'json'
  ): Promise<void> => {
    if (!facade.value || !toolGroupId.value) {
      throw new Error('工具组未创建');
    }

    try {
      console.log('[useTools] 导入标注:', format);

      await facade.value.importAnnotations({
        toolGroupId: toolGroupId.value,
        data,
        format,
      });

      // 刷新标注列表
      getAllAnnotations();

      console.log('[useTools] 标注导入成功');
    } catch (err: any) {
      console.error('[useTools] 导入标注失败:', err);
      error.value = err.message || '导入标注失败';
      throw err;
    }
  };

  /**
   * 销毁工具组
   */
  const destroyToolGroup = (): void => {
    if (!facade.value || !toolGroupId.value) {
      return;
    }

    try {
      console.log('[useTools] 销毁工具组:', toolGroupId.value);
      
      // 这里可能需要调用 facade 的清理方法
      toolGroupId.value = null;
      activeTool.value = null;
      registeredTools.value = [];
      annotations.value = [];
    } catch (err: any) {
      console.error('[useTools] 销毁工具组失败:', err);
      error.value = err.message || '销毁工具组失败';
    }
  };

  return {
    toolGroupId,
    activeTool,
    registeredTools,
    annotations,
    isLoading,
    error,
    createToolGroup,
    registerTool,
    registerTools,
    activateTool,
    deactivateTool,
    getAllAnnotations,
    removeAnnotation,
    clearAllAnnotations,
    exportAnnotations,
    importAnnotations,
    destroyToolGroup,
  };
}


